package org.oexam.ostudy.facade;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.oexam.ostudy.facade.struct.InsertUserDetails;
import org.oexam.ostudy.sl.ManageUsers;

public class CreateUserPage {
	
	public static final String USER_NAME_PATTERN = "^[A-Za-z][A-Za-z0-9]*";
	
	public static final String PASSWORD = "[A-Za-z0-9]{6}[A-Za-z0-9]*";
	
	public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" ;
		
	public static final String PHONE_NUMBER_PATTERN = "\\d{10}" ;
	
	public static final String TEACHER_RESPONSIBLE = "[0-9]+";
	
	//TODO Pradeep :  need to change return type.
	public String createUser(InsertUserDetails userDetails) {
		
		// TODO Pradeep : add sanity checks and call the SL method.
		String errString = "";
		
		// sanity check for userName;
		String userName = userDetails.getUserName().trim();

		Pattern pattern = Pattern.compile(USER_NAME_PATTERN);
	    Matcher matcher = pattern.matcher(userName);
	    
	    if (!matcher.matches()) {
	    	errString += "User name fromat is not proper, it should be Alpha Numeric and should start with character\n";
	    }
	    
	    String password = userDetails.getPassword().trim();
	    pattern = Pattern.compile(PASSWORD);
	    matcher = pattern.matcher(password);
	    
	    if (!matcher.matches()) {
	    	errString += "Password should be Alpha Numeric, with minimum 6 charaters\n";
	    }
	    
	    
		// sanity check for firstName
		String firstName = userDetails.getFirstName();
		firstName = firstName.trim();
		
		if (firstName == null){
			errString += "user name not entered\n";			
		}
		
		
		String lastName = userDetails.getLastName();
		lastName = lastName.trim();
		
		String address1 = userDetails.getAddress1().trim();
		String address2 = userDetails.getAddress2().trim();
		
		if ( (address1 == "") && (address2 == "")) {
			errString += "Address not entered\n";
		}
		
		// sanity check for phone number
		String phoneNumber = userDetails.getPhoneNumber().trim();
		
		pattern = Pattern.compile(PHONE_NUMBER_PATTERN);
	    matcher = pattern.matcher(phoneNumber);
	    
	    if (!matcher.matches()) {
	    	errString += "Phone Number must be 10-Digit number\n";
	    }
	    
	    // sanity check for email address
	    String emailAddress = userDetails.getEmailId();
	    	 
	    pattern = Pattern.compile(EMAIL_PATTERN);
	    matcher = pattern.matcher(emailAddress);
	    
	    if (!matcher.matches()) {
	    	errString += "Email Address is not proper\n";
	    }
	    
	    
	    
	    
	    
	    if (errString == "") {
	    	// add details to data_base
	    	ManageUsers  mngUser = new ManageUsers();
	    	String retString = mngUser.createUser(userDetails);
	    	
	    	errString += retString;
	    		    	
	    }
	    
	    
		return errString;				
	}

}
